<template>
  <div>
    <!-- 交付经理填写团队组建信息 -->
    <div class="desc-item">
      <div class="form-item">团队组建信息</div>
      <div v-if="isShowApprovalOperation('first')">
        <div class="responsive-table-container">
          <div class="table-title">添加团队成员</div>
          <!-- 团队成员列表表单 -->
          <el-table
            :data="membersForm.members"
            style="width: 100%"
            :class="{ 'small-screen': isSmallScreen }"
          >
            <el-table-column label="姓名" prop="user_name" min-width="120">
              <template #default="{ row }">
                <el-input v-model="row.user_name" />
              </template>
            </el-table-column>
            <el-table-column label="联系电话" prop="contact_information" min-width="150">
              <template #default="{ row }">
                <el-input v-model="row.contact_information" />
              </template>
            </el-table-column>
            <el-table-column label="部门" prop="department_name" min-width="120">
              <template #default="{ row }">
                <el-input v-model="row.department_name" />
              </template>
            </el-table-column>
            <el-table-column label="加入日期" prop="joining_date" min-width="150">
              <template #default="{ row }">
                <el-date-picker
                  v-model="row.joining_date"
                  placeholder="选择日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-value="new Date()"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="80">
              <template #default="{ $index }">
                <el-button type="danger" class="w-100%" @click="removeMembers($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="addMembers" class="mt-10px mb-20px">添加成员</el-button>
          <el-button type="primary" @click="importTeam('1')" class="mt-10px mb-20px"
            >批量导入</el-button
          >
          <TeamImportForm ref="importFormRef" :teamType="teamType" @get-team-data="getTeamData" />
        </div>
        <div class="responsive-table-container">
          <div class="table-title">添加合作伙伴</div>
          <!-- 合作伙伴列表表单 -->
          <el-table
            :data="partnersForm.members"
            style="width: 100%"
            :class="{ 'small-screen': isSmallScreen }"
          >
            <el-table-column label="姓名" prop="user_name" min-width="120">
              <template #default="{ row }">
                <el-input v-model="row.user_name" />
              </template>
            </el-table-column>
            <el-table-column label="联系电话" prop="contact_information" min-width="150">
              <template #default="{ row }">
                <el-input v-model="row.contact_information" />
              </template>
            </el-table-column>
            <el-table-column label="公司" prop="company" min-width="150">
              <template #default="{ row }">
                <el-input v-model="row.company" />
              </template>
            </el-table-column>
            <el-table-column label="加入日期" prop="joining_date" min-width="150">
              <template #default="{ row }">
                <el-date-picker
                  v-model="row.joining_date"
                  placeholder="选择日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="80">
              <template #default="{ $index }">
                <el-button type="danger" class="w-100%" @click="removePartners($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="addPartners" class="my-10px">添加合作伙伴</el-button>
          <el-button type="primary" @click="importTeam('2')" class="my-10px">批量导入</el-button>
        </div>
      </div>
      <div
        v-if="projectFiles[processStageName].length > 0"
        class="files-upload"
      >
        <div class="table-title">上传附件</div>
        <FilesUpload
          ref="filesUploadRef"
          :fileTypes="projectFiles[processStageName]"
          :projectInfo="projectInfo"
          :readOnly="!isShowApprovalOperation('first')"
          @getProjectFilesInfo="$emit('getProjectFilesInfo')"
        />
      </div>
      <div v-if="!isShowApprovalOperation('first')">
        <div class="table-title">团队成员</div>
        <el-table
          :data="mergedMembersList"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          style="width: 100%"
        >
          <el-table-column prop="user_name" label="姓名" />
          <el-table-column prop="contact_information" label="联系电话" />
          <!-- 合并部门和公司显示在一列 -->
          <el-table-column
            label="部门 / 公司"
            :formatter="(row) => `${row.department_name || row.company || ''}`"
          />
          <!-- 格式化加入日期，只显示日期部分 -->
          <el-table-column
            prop="joining_date"
            label="加入日期"
            :formatter="(row) => formatDate(row.joining_date, 'YYYY-MM-DD')"
          />
        </el-table>
      </div>

      <div v-if="isShowApprovalOperation('first')">
        <div class="form-item">审批信息</div>
        <ApprovalOpinion
          ref="approvalOpinionRef"
          v-model="approvalOpinionData" 
          required 
          label="审批意见"
        />
        <div class="mb-16 flex">
          <el-button
            class="ml-auto"
            type="primary"
            size="default"
            @click="approvalProcess('agree', 'projectManager')"
            >同意</el-button
          >
        </div>
      </div>
    </div>
  </div>
  <UserSelectDialog
    ref="userSelectDialog"
    :userSelectDialogProps="projectManagerProps"
    @update-selected-user="handleSelectedMemebers" 
    />
</template>

<script setup>
import * as KmsApi from '@/api/project/kms'
import * as BpmApi from '@/api/project/bpm'
import * as IctApi from '@/api/project/ict'
import DynamicDescription from '@/views/project/projectDetails/components/DynamicDescription.vue'
import UserSelectDialog from '@/views/project/projectDetails/components/UserSelectDialog.vue'
import FilesUpload from '@/views/project/projectDetails/components//FilesUpload.vue'
import { ref, toRefs, onMounted, onUnmounted } from 'vue'
import { formatDate } from '@/utils/formatTime'
import TeamImportForm from './TeamImportForm.vue'
import ApprovalOpinion from '@/views/project/components/ApprovalOpinion.vue'

const isSmallScreen = ref(false)

const checkScreenSize = () => {
  isSmallScreen.value = window.innerWidth < 768
}

onMounted(() => {
  checkScreenSize()
  window.addEventListener('resize', checkScreenSize)
})

onUnmounted(() => {
  window.removeEventListener('resize', checkScreenSize)
})

// emit事件合集
const emit = defineEmits(['getApprovalProcess', 'getProjectInfo', 'getProjectFilesInfo'])

// Props传值
const props = defineProps({
  isShowApprovalOperation: Function,
  projectInfo: Object,
  teamFormationDetails: Object,
  processStageName: String,
  taskName: String,
  role: String,
  processList: Array,
  projectFiles: Object
})
const {
  isShowApprovalOperation,
  projectInfo,
  teamFormationDetails,
  processStageName,
  taskName,
  role,
  processList
} = toRefs(props)

const mergedMembersList = [
  ...(projectInfo.value.members.teamMembers || []),
  ...(projectInfo.value.members.partner || [])
];

const projectManagerProps = ref({
  role: 'projectManager',
  execute_region: projectInfo.value.execute_region
})

// 动态详情组件ref对象
// const dynamicDescription = ref()
// 审批意见
const approvalOpinionData = ref('同意')
const approvalOpinionRef = ref()

// 创建对文件上传子组件的引用
const filesUploadRef = ref(null);
// 用户选择模态框
const userSelectDialog = ref()
// 已选中人员对象
const selectedMember = ref({})

// 添加团队成员表单
const membersForm = ref({
  members: []
})

// 下载附件
const downloadFile = (file) => {
  const params = {
    doc_id: file.doc_id,
    is_preview: false
  }
  KmsApi.previewAndDownloadFile(params).then((res) => {
    const downloadFileName = file.file_name
    const blobData = new Blob([res])
    const fileUrl = URL.createObjectURL(blobData)
    const link = document.createElement('a')
    link.href = fileUrl
    link.setAttribute('download', downloadFileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(fileUrl)
  })
}

// 添加团队成员
const addMembers = () => {
  openMemeberSelect()
  handleSelectedMemebers
}

// 删除团队成员
const removeMembers = (index) => {
  membersForm.value.members.splice(index, 1)
}

//批量导入团队成员
const importFormRef = ref()
const teamType = ref()
const importTeam = (type) => {
  teamType.value = type
  importFormRef.value.open()
}

//导入团队成员数据
const teamData = ref([])
const getTeamData = (val) => {
  teamData.value = val.data
  teamData.value.forEach((item) => {
    if (item.userId != null) {
      membersForm.value.members.push({
        user_name: item.userName,
        contact_information: item.contactInformation,
        department_name: item.departmentName,
        company: item.departmentName,
        joining_date: formatDate(new Date(item.joiningDate))
      })
    } else {
      partnersForm.value.members.push({
        user_name: item.userName,
        contact_information: item.contactInformation,
        department_name: item.departmentName,
        company: item.departmentName,
        joining_date: formatDate(new Date(item.joiningDate))
      })
    }
  })
}

// 添加合作伙伴成员表单
const partnersForm = ref({
  members: []
})
// 添加合作伙伴成员
const addPartners = () => {
  partnersForm.value.members.push({
    user_name: '',
    contact_information: '',
    department_name: '',
    company: '',
    joining_date: formatDate(new Date())
  })
}

// 删除合作伙伴成员
const removePartners = (index) => {
  partnersForm.value.members.splice(index, 1)
}

// 打开选择用户模态框
const openMemeberSelect = () => {
  userSelectDialog.value.userSelectVisible = true
  userSelectDialog.value.currentFieldName = 'selectedMembers'
}

// 选中团队成员事件
const handleSelectedMemebers = ({ userList, fieldName }) => {
  selectedMember.value = {
    user_name: '',
    contact_information: '',
    department_name: '',
    company: '',
    joining_date: ''
  }
  if (userList && userList[0]) {
    selectedMember.value.user_id = userList[0].id ?? selectedMember.value.user_id
    selectedMember.value.user_name = userList[0].nickname ?? selectedMember.value.user_name
    selectedMember.value.contact_information =
      userList[0].mobile ?? selectedMember.value.contact_information
    selectedMember.value.department_name =
      userList[0].dept_name ?? selectedMember.value.department_name
    selectedMember.value.joining_date = formatDate(new Date())
    membersForm.value.members.push(selectedMember.value)
  }
}

const approvalProcess = async (result, currentRole) => {
  try {
    if(approvalOpinionRef.value) {
      await approvalOpinionRef.value.validateForm()
    }

    if (filesUploadRef.value && !filesUploadRef.value?.validateFiles()) {
      return;
    }
    ElMessageBox.confirm(`是否${result === 'agree' ? '同意' : '驳回'}该流程单？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      // const approvalFormData = dynamicDescription.value.getFormData()

      if (result === 'agree') {
        const agreeProcessData = {
          assignedUserIds: [],
          id: processList.value[0].id,
          // reason: approvalFormData.reason || '同意',
          reason: '同意',
          copyUserIds: [],
          variables: {}
        }

        partnersForm.value.members = partnersForm.value.members.filter(
          (member) => member.user_name !== ''
        )

        const agreeTeamMembersData = [
          ...membersForm.value.members,
          ...partnersForm.value.members
        ].map((member) => ({
          ...member,
          project_code: projectInfo.value.project_code,
          project_name: projectInfo.value.project_name
        }))

        const agreeData = {
          project_index_do: projectInfo.value,
          task_approve_req_vo: agreeProcessData,
          project_team_member_list: agreeTeamMembersData
        }
        IctApi.agreeTeamFormationProcess(agreeData).then(() => {
          emit('getApprovalProcess')
          emit('getProjectInfo')
        })
      } else if (result === 'refuse') {
        const refuseData = {
          id: processList.value[0].id,
          // reason: approvalFormData.reason || '不同意'
          reason: '不同意'
        }
        await IctApi.refuseTestRunProcess(refuseData).then(() => {
          emit('getApprovalProcess')
        })
      }
      ElMessage({
        type: 'success',
        message: '提交成功'
      })
    })
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '请按照格式要求填写信息'
    })
  }

}

</script>

<style lang="scss" scoped>
@import url('@/views/project/projectDetails/styles/transfer.css');

.responsive-table-container {
  overflow-x: auto;
}

.files-upload {
  margin-top: 10px;
}

.small-screen :deep(.el-table__body-wrapper) {
  overflow-x: visible;
}

.small-screen :deep(.el-table__body) {
  display: block;
}

.small-screen :deep(.el-table__row) {
  display: flex;
  flex-direction: column;
  border-bottom: 1px solid #ebeef5;
  padding: 10px 0;
}

.small-screen :deep(.el-table__cell) {
  display: flex;
  align-items: center;
  padding: 5px 0;
  border: none;
}

.small-screen :deep(.el-table__cell::before) {
  content: attr(data-label);
  font-weight: bold;
  margin-right: 10px;
  min-width: 100px;
}
</style>